//node脚本，测试服务器

var http = require('http');
var url = require('url');

var resJson;

var app = (function(){
	var holder = [];
	function get(path,fn){
		if(!path) return;
		
		var has = false;
		for(var i=0;i<holder.length;i++){
			if(holder[i].path === path){
				has = true;
				holder[i].fn = fn;
				break;
			}
		}
		if(!has){
			holder.push({path:path,fn:fn});
		}
		
	}
	
	function render(req,res){
		// 解析请求，包括文件名
		var pathname = url.parse(req.url).pathname;
		var hasPath = false;
		
		var fn;
		
		for(var i=0;i<holder.length;i++){
			if(holder[i].path == pathname){
				hasPath = true;
				break;
			}
		}
		
		if(hasPath){
			res.writeHead(200, {
				'Content-Type' : 'text/html'
			});
			
			if(typeof holder[i].fn === "function"){
				holder[i].fn(req,res);
			}
		}
		else{
			res.writeHead(200, {
				'Content-Type' : 'text/html'
			});
			resJson.code=404;
			resJson.msg="err";
			res.write(JSON.stringify(resJson));
		}
		res.end();
	}

	function put(path,fn){get(path,fn);}
	function post(path,fn){get(path,fn);}
	function delet(path,fn){get(path,fn);}
	return {render,get,put,post,delet};
})();


app.get("/",function(req,res){
	 res.write("This is test home page.");
 });

app.get("/user",function(req,res){
	resJson.data = {name:"呵呵哒",age:15,sex:"男",des:"这个人很Q。"};
	
	res.write(JSON.stringify(resJson));
	
});

 
 
 
// 创建服务器
http.createServer(function(req, res) {
	resJson = {code:200,msg:"",data:null}; 
	app.render(req,res);
	// 发送响应数据
}).listen(3000);


// 控制台会输出以下信息
console.log('Server running at http://127.0.0.1:3000/');